package beans;

import dao.RoleDAO;
import dao.UserDAO;
import model.User;
import utils.GetBeanUtil;
import utils.UpdateUtil;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import java.io.IOException;
import java.util.List;

@ManagedBean(name = "userBean")
@SessionScoped
public class UserBean {
    private User user;
    private String login;
    @PostConstruct
    public void init() {
        user = new User();
        RoleDAO roleDAO = new RoleDAO();
        user.setRole(roleDAO.getRoleById(1));
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public void signIn() {
        try {
            boolean flag = false;
            UserDAO userDAO = new UserDAO();
            List<User> users = userDAO.getAllUsers();
            for (User u : users) {
                if (u.getLogin().equals(user.getLogin()) && u.getPassword().equals(user.getPassword())) {
                    user = u;
                    UpdateUtil.updatePage();
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success", "You have successfully registered"));
                    flag = true;
                    break;
                }
            }
            if(!flag) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error", "Incorrect login or password"));
            }
        }
        catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", e.toString()));
        }
    }

    public void signOut() throws IOException{
        init();
        NavigationBean navigationBean = (NavigationBean) GetBeanUtil.getBean("navigationBean");
        navigationBean.action("main.xhtml");
    }

    public String getUserLoginById(int id) {
        UserDAO userDAO = new UserDAO();
        return userDAO.getUserById(id).getLogin();
    }

}
